<template>
	<el-form
		:model="ruleForm"
		ref="ruleForm"
		label-width="100px"
		class="form"
	>
		<div
			class="container"
			v-for="(item, index) in questionData"
			:key="item.id"
		>
			<div class="VSTD_box_item_title">
				<!-- 题目的信息 -->

				<p style="font-weight: 700">
					第{{ index + 1 }}题：{{ item.content }}
					<span v-if="item.questionType == 1">（单选）</span>
					<span v-if="item.questionType == 2">（判断）</span>
					<span v-if="item.questionType == 3">（简答）</span>
				</p>
			</div>
			<!-- 如果是选择题 -->
			<div v-if="item.questionType == 1" class="choiceBox">
				<el-form-item label="" prop="resource">
					<el-radio-group
						v-model="answers[index]"
						@click="updateColor(index, 1)"
					>
						<el-radio :label="1">{{ item.option1 }}</el-radio>
						<el-radio :label="2">{{ item.option2 }}</el-radio>
						<el-radio :label="3">{{ item.option3 }}</el-radio>
						<el-radio :label="4">{{ item.option4 }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<div class="aswer-box" v-if="isVisible">
					<answerBox
						:userAsw="answers[index]"
						:correctAsw="item.answer"
					></answerBox>
				</div>
				<el-divider />
			</div>
			<!-- 如果是判断题 -->
			<div v-if="item.questionType == 2">
				<el-form-item label="" prop="resource">
					<el-radio-group
						v-model="answers[index]"
						@change="updateColor(index, 1)"
					>
						<el-radio :label="1">{{ item.option1 }}</el-radio>
						<el-radio :label="2">{{ item.option2 }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<div class="aswer-box" v-if="isVisible">
					<answerBox
						:userAsw="answers[index]"
						:correctAsw="item.answer"
					></answerBox>
				</div>
				<el-divider />
			</div>

			<div
				v-if="item.questionType == 3"
				class="VSTD_box_item_select"
			>
				<el-form-item label="" prop="resource">
					<div class="input">
						<el-input
							type="textarea"
							v-model="answers[index]"
							@change="updateColor(index, 1)"
						></el-input>
					</div>
				</el-form-item>
				<div class="aswer-box" v-if="isVisible">
					<answerBox
						:userAsw="answers[index]"
						:correctAsw="item.answer"
					></answerBox>
				</div>
				<el-divider />
			</div>
		</div>
		<div class="submitButton">
			<el-button type="success" @click="openMessage">
				提交
			</el-button>
			<el-button
				@click="backHome"
				style="margin-left: 30px"
				v-if="accessToHome"
			>
				回到主页
			</el-button>
		</div>
	</el-form>
</template>

<script lang="ts" setup>
import { Ref, onMounted, ref } from 'vue'
import { getAllQuestions, Question } from '@/api/test/wirttenTest.ts'
import $bus from '@/bus/index'
import answerBox from './answerBox.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createLeveExam } from '@/api/test/examHistory'
// import {type ExamHistory } from '@/api/test/examHistory'
import { formatDateTime } from '@/utils/formatDate'
// import useUserStore from '@/store/modules/user'
import router from '@/router'

//表单数据
const ruleForm = ref({})
const questionData: Ref<Question[]> = ref([])
const isVisible = ref(false)
// const isShowScore = ref(false)
const accessToHome = ref(false)
//全局事件总线，用改变颜色
const updateColor = (index: number, value: number) => {
	$bus.emit('updateColors', { index, value })
}
//用于记录用户的答案信息
const answers = ref(new Array(questionData.value.length).fill(null))
//初始化
onMounted(() => {
	initQuestionData()
	start()
})
//用于获取题目信息
const getQuestions = async (pageNum: number, pageSize: number) => {
	const res = await getAllQuestions(pageNum, pageSize)
	questionData.value = res
}

//用于判断题目类型
function categorizeQuestions(question: Question): number {
	const { option1, option2, option3, option4 } = question

	if (option1 && option2 && option3 && option4) {
		return 1
	} else if (option1 && option2) {
		return 2
	} else {
		return 3
	}
}
async function initQuestionData() {
	await getQuestions(1, 50)
	questionData.value = questionData.value.map(question => ({
		...question,
		questionType: categorizeQuestions(question)
	}))
}
const startTime: any = ref('')
function start() {
	startTime.value = formatDateTime(new Date())
}
//计算分数
let score = ref(0)
function calculateScore(answers: any[]) {
	for (let i = 0; i < answers.length; i++) {
		let userAnswer = null
		if (answers[i] == 1) {
			userAnswer = questionData.value[i].option1
		} else if (answers[i] == 2) {
			userAnswer = questionData.value[i].option2
		} else if (answers[i] == 3) {
			userAnswer = questionData.value[i].option3
		} else if (answers[i] == 4) {
			userAnswer = questionData.value[i].option4
		}

		if (userAnswer == questionData.value[i].answer) {
			score.value = score.value + 2
			console.log('第' + (i + 1) + '题：' + '正确')
			questionData.value[i].isCorrect = true
		} else {
			questionData.value[i].isCorrect = false
		}
	}
	return score.value
}

// const useStore = useUserStore()
const requestForm: Ref<any> = ref()
function submit() {
	try {
		// const endTime = formatDateTime(new Date()) // 记录结束时间
		console.log('用户答案：', answers)
		score.value = calculateScore(answers.value)
		console.log('得分：', score, '分')
		// requestForm.value = {
		// 	userId: useStore.userId,
		// 	score: score.value,
		// 	startTime: startTime.value,
		// 	endTime: endTime
		// }
		createLeveExam(requestForm.value)
		isVisible.value = true
		accessToHome.value = true
	} catch (e) {
		console.log('提交出错')
		console.log(e)
	}
}
const openMessage = () => {
	ElMessageBox.confirm('确认提交本次考试答案吗？', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(async () => {
			submit()
			console.log('提交成功')
			ElMessage({
				type: 'success',
				message: '提交成功'
			})
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '取消提交'
			})
		})
}
function backHome() {
	router.push('/home')
}
</script>
<style>
.form {
	font-size: 20px;
	font-family: 'Courier New', Courier, monospace;
}
.input {
	width: 440px;
	margin-top: 10px;
}
.el-radio-group,
.input {
	margin-left: -90px;
}
.submitButton {
	display: flex;
	justify-content: center;
	align-items: center;
}
.answer-box {
	display: flex;
	justify-content: center;
	align-items: center;
	background-color: aqua;
	width: 100px;
	height: 100px;
}
.container{
	width: 100%;
	height: 100%;
}
</style>
